<?

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Library of functions for core functions to reference
 *
 * @package   blocks-email_list
 * @author    Tyler Bannister <tyler.bannister@remote-learner.net>
 * @copyright 2011 by Remote Learner - http://www.remote-learner.net/
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

/**
 * Output the file
 *
 * @author Tyler Bannister <tyler.bannister@remote-learner.net>
 * @param object $course course settings object
 * @param object $context context object
 * @param string $component the name of the component we are serving files for.
 * @param string $filearea the name of the file area.
 * @param array $args the remaining bits of the file path.
 * @param bool $forcedownload whether the user must be forced to download the file.
 * @return void (no point in returning anything, we have to die per the Moodle design)
 * @uses $DB
 * @uses $USER
 */
function block_email_list_pluginfile($course, $birecord, $context, $filearea, $args, $forcedownload) {
    global $DB, $USER;

    $fs   = get_file_storage();
    $show = false;

    $sender = $DB->get_field('block_email_list_mail', 'userid', array('id' => $args[0]));
    if ($sender == $USER->id) {
        $show = true;
    }

    if (! $show) {
        $mailids  = $DB->get_records('block_email_list_send', array('mailid' => $args[0]), 'userid', 'userid');
        foreach ($mailids as $mailid) {
            if ($USER->id == $mailid->userid) {
                $show = true;
                break;
            }
        }
    }

    if ($show) {
        $file = $fs->get_file($context->id, 'block_email_list', $filearea, $args[0], '/', $args[1]);

        if ($file && (! $file->is_directory())) {
            session_get_instance()->write_close(); // unlock session during fileserving
            send_stored_file($file, 0, 0, $forcedownload);
        }
    }
    send_file_not_found();
}